<?php
/**
 * Created by PhpStorm.
 * User: muhe0
 * Date: 2017/11/28
 * Time: 17:00
 */
namespace Lin\Dnah;
use DebugBar\DataCollector\TimeDataCollector;
use Illuminate\Support\Facades\Log;
use PhpParser\Node\Name;

class  Manag {
    const  NAME="application";
    protected  $app;
    /**
     * 利用debugBar 的组件
     * @var TimeDataCollector
     */
    protected  $collector;

    /**
     * @return TimeDataCollector
     */
    public function getCollector()
    {
        return $this->collector;
    }

    /**
     *
     * @param mixed $collector
     */
    public function setCollector($collector)
    {
        $this->collector = $collector;
    }
    public function __construct($app = null)
    {
        if (!$app) {
            $app = app();   //Fallback when $app is not given
        }
        $this->app = $app;
    }
    //启动计时程序
    public function start(){

        $hjas=$this->getCollector()->hasStartedMeasure(self::NAME);
        if(!$hjas){
            $this->getCollector()->startMeasure(self::NAME);
        }
    }
    private $timemeta=null;

    /**
     * 返回Application耗用的时间
     * @return null
     */
    public function getTimemeta(){
       return $this->timemeta ;
    }
    //程序结束时的回调
    public function onShutdown($calls){
        if(!is_array($calls) )return ;
        $con=$this->getCollector();
        $meas=$con->getMeasures();
        if(empty($meas)){
            $_=$con->collect();
            $meas=$con->getMeasures();
        }
        $meadata=false;
        foreach ($meas as  $mea){
            if( strtolower( $mea['label']) ==self::NAME){
                $meadata=$mea; break ;
            }
        }
        if($meadata){
            $this->timemeta = $meadata ;
            foreach ($calls as  $obj){
                try{
                    call_user_func_array(array(new $obj,'shut'),[$meadata]);
                }catch (\Exception $e){
                    throw $e;
                }
            }
        }
    }

}
